package initialize

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"server/dbtools/gorm_db"

	"server/config"
	"server/global"
)

func InitTimer() {
	if global.XidwConfig.Timer.Start {
		for i := range global.XidwConfig.Timer.Detail {
			go func(detail config.Detail) {
				var option []cron.Option
				if global.XidwConfig.Timer.WithSeconds {
					option = append(option, cron.WithSeconds())
				}
				_, err := global.XidwTimer.AddTaskByFunc("ClearDB", global.XidwConfig.Timer.Spec, func() {
					err := gorm_db.ClearTable(global.SysDB, detail.TableName, detail.CompareField, detail.Interval)
					if err != nil {
						global.Logger.Info(fmt.Sprintf("timer error:%v", err))
					}
				}, option...)
				if err != nil {
					global.Logger.Info(fmt.Sprintf("add timer error:%v", err))
				}
			}(global.XidwConfig.Timer.Detail[i])
		}
	}
}
